<!--
 * Copyright (c) 2113-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'wms:wh:rd11:wmsRd11:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #childList>
        <BasicTable
          @register="registerWmsRds11Table"
          @row-click="handleWmsRds11RowClick"
        />
        <!-- <a-button class="mt-2" @click="handleWmsRds11Add" v-auth="'wms:wh:rd11:wmsRd11:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsWhRd11WmsRd11Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { WmsRd11, wmsRd11Save, wmsRd11Form } from '/@/api/wms/wh/rd11/wmsRd11';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wms.wh.rd11.wmsRd11');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<WmsRd11>({} as WmsRd11);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: t('查看材料出库单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('出库单号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
        disabled: true,
      },
      rules: [{ required: true }],
    },
    {
      label: t('申请单号'),
      field: 'ccode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
        disabled: true,
      },
      rules: [{ required: true }],
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        disabled: true,
      },
    },
    {
      label: t('存货编码'),
      field: 'invCode',
      required: true,
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
    },
    {
      label: t('存货名称'),
      field: 'invCode',
      fieldLabel: 'basInv.invName',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      required: true,
    },
    {
      label: t('规格型号'),
      field: 'basInv.cinvStd',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
    },
    {
      label: t('计量单位'),
      field: 'basInv.unitName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
    },
    {
      label: t('出库仓库'),
      field: 'basWare.cwhname',
      component: 'Input',
      componentProps: {
        maxlength: 16,
        disabled: true,
      },
    },
    {
      label: t('累计数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
        disabled: true,
      },
    },
    {
      label: t('累计件数'),
      field: 'inum',
      component: 'Input',
      componentProps: {
        maxlength: 16,
        disabled: true,
      },
    },
    {
      label: t('出库明细'),
      field: 'info1',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'childList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerWmsRds11Table, wmsRds11Table] = useTable({
    // actionColumn: {
    //   width: 30,
    //   // actions: (record: Recordable) => [
    //   //   {
    //   //     icon: 'i-ant-design:delete-outlined',
    //   //     color: 'error',
    //   //     popConfirm: {
    //   //       title: '是否确认删除',
    //   //       confirm: handleWmsRds11Delete.bind(this, record),
    //   //     },
    //   //     auth: 'wms/pu:rd11:wmsRd11:edit',
    //   //   },
    //   // ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    indexColumnProps: { width: 40 },
  });

  async function setWmsRds11TableData(_res: Recordable) {
    wmsRds11Table.setColumns([
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('件数'),
        dataIndex: 'inum',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('换算率'),
        dataIndex: 'ichangeRate',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('批次'),
        dataIndex: 'cbatch',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('货位'),
        dataIndex: 'basPos.posName',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        // 判断basInv.binvbatch 为1时显示
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 150,
        align: 'left',
        editRow: true,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
    ]);
    wmsRds11Table.setTableData(record.value.childList || []);
  }

  function handleWmsRds11RowClick(record: Recordable) {
    //record.onEdit?.(true, false);
  }

  function handleWmsRds11Add() {
    wmsRds11Table.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleWmsRds11Delete(record: Recordable) {
    wmsRds11Table.deleteTableDataRecord(record);
  }

  async function getChildList() {
    let childListValid = true;
    let childList: Recordable[] = [];
    for (const record of wmsRds11Table.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        childListValid = false;
      }
      childList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of wmsRds11Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      childList.push({
        ...record,
        status: '1',
      });
    }
    if (!childListValid) {
      throw { errorFields: [{ name: ['childList'] }] };
    }
    return childList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await wmsRd11Form(data);
    record.value = (res.wmsRd11 || {}) as WmsRd11;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setWmsRds11TableData(res);
    updateSchema([
      {
        field: 'djno',
        componentProps: {
          disabled: true,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.childList = await getChildList();
      // console.log('submit', params, data, record);
      const res = await wmsRd11Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
